package cn.devcat.sso.config.security.filter;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import cn.devcat.sso.entity.DevcatApiPattern;
import cn.devcat.sso.entity.DevcatRole;
import cn.devcat.sso.service.IDevcatApiPatternService;
import cn.devcat.sso.service.IDevcatRoleService;

@Component
public class DevcatFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	
	@Autowired
	IDevcatApiPatternService apiPatternService;
	@Autowired
	IDevcatRoleService roleService;

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		AntPathMatcher matcher = new AntPathMatcher();
		String requestUrl = ((FilterInvocation)object).getRequestUrl();
		List<DevcatApiPattern> list = apiPatternService.getAllApiParrentList();
		for(DevcatApiPattern apiPattern : list) {
			if(matcher.match(apiPattern.getApiPattern(), requestUrl)) {
				List<DevcatRole> roleListByApiPatternId = roleService.getRoleListByApiPatternId(apiPattern.getId());
				if(roleListByApiPatternId == null || roleListByApiPatternId.isEmpty()) {
					return SecurityConfig.createList("ROLE_ADMIN");
				}
				List<String> roles = roleListByApiPatternId.stream().map(DevcatRole::getRoleCode).collect(Collectors.toList());
				return SecurityConfig.createList(roles.toArray(new String[roles.size()]));
			}
		}
		return SecurityConfig.createList("ROLE_ADMIN");
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	
}
